package org.kia.data.adapters.droidfu;


import java.net.ConnectException;

import org.apache.http.params.HttpParams;
import org.kia.data.adapters.RequestAdapter;
import org.kia.data.adapters.ResponseAdapter;

import android.os.Bundle;
import android.util.Log;

import com.github.droidfu.http.BetterHttpRequest;

/**
 * @author Amir Lazarovich
 */
public class DroidFuRequestAdapter implements RequestAdapter {

    private static final String TAG = "DroidFuRequestAdapter";
    private static final int NOT_FOUND = -1;

    private BetterHttpRequest mRequest;

    /**
     * Constructs a new DroidFuRequestAdapter
     *
     * @param request
     */
    public DroidFuRequestAdapter(BetterHttpRequest request) {
        mRequest = request;
    }


    @Override
    public void addParams(Bundle params) {
        if (params == null) {
            // No params given
            return;
        }

        HttpParams requestParams = mRequest.unwrap().getParams();
        String value;
        for (String key : params.keySet()) {
            value = params.getString(key);
            if (value != null) {
                addParam(requestParams, key, value);
            } else {
                Log.w(TAG, "Unsupported parameter type");
            }
        }
    }

    /**
     * Append parameter to requestParams and update {@link #mFullRequest} with the
     * new value
     *
     * @param requestParams
     * @param key
     * @param value
     */
    protected void addParam(HttpParams requestParams, String key, String value) {
        requestParams.setParameter(key, value);
    }

    @Override
    public void setUri(String uri) {
        throw new UnsupportedOperationException("Droid-Fu doesn't support this functionality");
    }

    @Override
    public ResponseAdapter send() throws ConnectException {
        return new DroidFuResponseAdapter(mRequest.send());
    }

    @Override
    public String toString() {
        return mRequest.getRequestUrl();
    }

    /**
     * Get the representative key of this request. <br/> Basically it's merely the full URL including its GET
     * parameters
     *
     * @return
     */
    @Override
    public String getKey() {
        return mRequest.getRequestUrl();
    }
}
